package com.goldplusgold.tradedelay.app.trade.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.utils.MathUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.StringConvertNumber;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.TitleView;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.network.lib.http.netty.ChannelManager;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.base.listeners.Interface;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.tradedelay.app.base.widget.TDDropDownView;
import com.goldplusgold.tradedelay.app.base.widget.TDSureOrderDialog;
import com.goldplusgold.tradedelay.app.main.activity.TDMainActivity;
import com.goldplusgold.tradedelay.app.market.eventbus.DynaMessageEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.FiveRangeMessageEvent;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.tradedelay.app.trade.activity.TradeAccountActivity;
import com.goldplusgold.tradedelay.app.trade.adapter.AdapterContent;
import com.goldplusgold.tradedelay.app.trade.eventbus.ContractTypeEvent;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.EntrustStatus;
import com.goldplusgold.tradedelay.app.trade.pojo.MyAssets;
import com.goldplusgold.tradedelay.app.trade.pojo.OrderResult;
import com.goldplusgold.tradedelay.app.trade.pojo.PositionType;
import com.goldplusgold.tradedelay.app.trade.pojo.TDTradeType;
import com.goldplusgold.ui.lib.keyboard.KeyboardTouchListener;
import com.goldplusgold.ui.lib.keyboard.KeyboardUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;


public class TradeFragment extends BaseFragment implements KeyboardUtil.KeyBoardHeadListener, Handler.Callback {
    @BindView(R.id.title_view_trade)
    TitleView titleView;
    @BindView(R.id.newest_goldprice)
    TextView newestGoldprice;
    @BindView(R.id.minus_price_btn)
    ImageView minusPriceBtn;
    @BindView(R.id.plus_price_btn)
    ImageView plusPriceBtn;
    @BindView(R.id.minus_quantity_btn)
    ImageView minusQuantityBtn;
    @BindView(R.id.plus_quantity_btn)
    ImageView plusQuantityBtn;
    @BindView(R.id.activity_tdmake_order)
    LinearLayout activityTdmakeOrder;
    @BindView(R.id.sold_one_price)
    public TextView soldOnePrice;
    @BindView(R.id.sold_one_quantity)
    TextView soldOneQuantity;
    @BindView(R.id.buy_one_price)
    public TextView buyOnePrice;
    @BindView(R.id.buy_one_quantity)
    TextView buyOneQuantity;
    @BindView(R.id.buy_two_price)
    TextView buyTwoPrice;
    @BindView(R.id.buy_two_quantity)
    TextView buyTwoQuantity;
    @BindView(R.id.choose_type)
    TextView chooseType;
    @BindView(R.id.choose_type_layout)
    RelativeLayout chooseTypeLayout;
    @BindView(R.id.drop_stop_price)
    TextView dropStopPrice;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.dynamic_equity)
    TextView dynamicEquity;
    @BindView(R.id.available_amount)
    TextView availableAmount;
    @BindView(R.id.sold_two_price)
    TextView soldTwoPrice;
    @BindView(R.id.sold_two_quantity)
    TextView soldTwoQuantity;
    @BindView(R.id.gold_rose)
    TextView goldRose;
    @BindView(R.id.amount_layout)
    RelativeLayout amountLayout;
    @BindView(R.id.id_text_view_lasted_price)
    TextView idTextViewLastedPrice;
    @BindView(R.id.id_text_view_stop_price)
    TextView idTextViewStopPrice;
    @BindView(R.id.id_text_view_price)
    TextView idTextViewPrice;
    @BindView(R.id.harden_price)
    TextView hardenPrice;
    @BindView(R.id.plus_price_layout)
    RelativeLayout plusPriceLayout;
    @BindView(R.id.minus_quantity_layout)
    RelativeLayout minusQuantityLayout;
    @BindView(R.id.plus_quantity_layout)
    RelativeLayout plusQuantityLayout;
    @BindView(R.id.buy_price)
    TextView buyPrice;
    @BindView(R.id.sold_price)
    TextView soldPrice;
    //底部切换模块
    @BindView(R.id.td_view_pager_bottom)
    ViewPager mViewPager;
    @BindView(R.id.id_tab_home)
    RadioButton idTabHome;
    @BindView(R.id.id_tab_market)
    RadioButton idTabMarket;
    @BindView(R.id.id_tab_trade)
    RadioButton idTabTrade;
    @BindView(R.id.id_tab_menu)
    RadioGroup idTabMenu;
    @BindView(R.id.id_line_home)
    ImageView idLineHome;
    @BindView(R.id.id_line_market)
    ImageView idLineMarket;
    @BindView(R.id.id_line_trade)
    ImageView idLineTrade;
    @BindView(R.id.buy_btn_tradetype_txt)
    TextView buyBtnTradetypeTxt;
    @BindView(R.id.sold_btn_trade_type_txt)
    TextView soldBtnTradeTypeTxt;
    @BindView(R.id.close_position_price)
    public TextView closePositionPrice;
    @BindView(R.id.remind_info)
    TextView remindInfo;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.remind_layout)
    RelativeLayout remindLayout;
    @BindView(R.id.iv_complete)
    ImageView ivComplete;
    @BindView(R.id.iv_warn)
    ImageView ivWarn;
    private int mPosition = 0;
    private int currentQuantity = 0;
    private final int HIDE_REMIND_HEAD = 5;
    private BigDecimal currentUnitPrice = new BigDecimal(0);
    private String mTradeType = "黄金延期Au(T+D)";
    private String mTradeTypeCode = "Au(T+D)";
    private int mTypeFlag = 0;//0,1指黄金类型
    private int priceType = 0;
    private boolean isgetPrice;
    private Market.InstType instType = Market.InstType.AU_TD;//初始化合约类型
    private final int TYPE_RIVAL_PRICE = 0;//对手价
    private final int TYPE_QUEUING_PRICE = 1;//排队价
    private final int TYPE_NEWEST_PRICE = 2;//最新价
    /*持仓类型*/
    private String currentPositionType;
    private final String NO_POSITION = "0";//无持仓
    private final String SHORT_POSITIONS = "1";//持空仓
    private final String MULTIPLE_POSITIONS = "2";//持多仓
    private final String SHORT_AND_MULTIPLE_POSITIONS = "3";//持多/空仓
    private String shortOrLongValue;
    /*下单参数*/
    private String mPositionTypeCode;
    private String mUnitPrice;
    private int totalVolume;
    private ViewGroup viewGroup;// 动画层
    private String lastestPriceValue;
    private String buyOnePriceValue;
    private String soldOnePriceValue;
    /*合约持仓总量*/
  /*  private int auTotalAmount = 0;
    private int mAuTotalAmount = 0;
    private int agTotalAmount = 0;*/
    private KeyboardUtil keyboardUtil;
    private Timer timer;

    private Handler handler;

    public static TradeFragment newInstance() {

        Bundle args = new Bundle();
        TradeFragment fragment = new TradeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler(this);
        EventBus.getDefault().register(this);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        //得到InputMethodManager的实例
        if (imm.isActive()) {
            //如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
            //关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_trade;
    }

    public void initView() {
        if (getActivity() != null && getActivity() instanceof TDMainActivity) {
            int visibility = ((TDMainActivity) getActivity()).mTabMenu.getVisibility();
            if (View.GONE == visibility) {
                ((TDMainActivity) getActivity()).mTabMenu.setVisibility(View.VISIBLE);
            }
        }
        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText("下单");
        titleView.getTDMoreView().setVisibility(View.VISIBLE);
        titleView.getTDMoreView().setImageResource(R.drawable.icon_more);
        titleView.getTDMoreView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TradeAccountActivity.class);
                startActivity(intent);
            }
        });
        initEditText();
        initViewPager();
    }

    private void initEditText() {
        keyboardUtil = ((TDMainActivity) getActivity()).getKeyBoardUtil();
        keyboardUtil.setmKeyBoardHeadListener(this);
        etPrice.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM_POINT, KeyboardTouchListener.TYPE_TOP));
        setAmoutInputType(keyboardUtil);
        etPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.indexOf(".") > 2) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 3);
                        etPrice.setText(inputString);
                        etPrice.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().equals(".")) {
                    inputString = "0";
                    etPrice.setText(inputString);
                    etPrice.setSelection(1);
                }
                if (inputString.startsWith("0") && inputString.trim().length() > 1) {
                    if (!inputString.substring(1, 2).equals(".")) {
                        etPrice.setText(inputString.subSequence(1, 2));
                        etPrice.setSelection(1);
                        return;
                    }
                }
                if (inputString.length() > 0) {
                    isgetPrice = true;
                    currentUnitPrice = MathUtils.stringToBigDecemal(inputString.trim());
                    etPrice.setSelection(etPrice.getText().length());
                    setTradeButtonText(inputString, inputString);
                    if (!TextUtils.isEmpty(closePositionPrice.getText())) {
                        if ("锁 仓".equals(closePositionPrice.getText().toString().trim()) || "无持仓".equals(closePositionPrice.getText().toString().trim())) {
                            return;
                        }
                        closePositionPrice.setText(inputString);
                    }
                } else {
                    switch (priceType) {
                        case TYPE_RIVAL_PRICE:
                            setTradeButtonText(soldOnePriceValue, buyOnePriceValue);
                            currentUnitPrice = MathUtils.stringToBigDecemal(soldOnePriceValue);
                            if (!TextUtils.isEmpty(shortOrLongValue))
                                if ("多".equals(shortOrLongValue)) {
                                    closePositionPrice.setText(buyOnePriceValue);
                                } else {
                                    closePositionPrice.setText(soldOnePriceValue);
                                }
                            break;
                        case TYPE_QUEUING_PRICE:
                            setTradeButtonText(buyOnePriceValue, soldOnePriceValue);
                            currentUnitPrice = MathUtils.stringToBigDecemal(buyOnePriceValue);
                            if (!TextUtils.isEmpty(shortOrLongValue)) {
                                if ("多".equals(shortOrLongValue)) {
                                    closePositionPrice.setText(soldOnePriceValue);
                                } else {
                                    closePositionPrice.setText(buyOnePriceValue);
                                }
                            }
                            break;
                        case TYPE_NEWEST_PRICE:
                            setTradeButtonText(lastestPriceValue, lastestPriceValue);
                            currentUnitPrice = MathUtils.stringToBigDecemal(lastestPriceValue);
                            if (!TextUtils.isEmpty(closePositionPrice.getText())) {
                                if ("锁 仓".equals(closePositionPrice.getText().toString()) || "无持仓".equals(closePositionPrice.getText().toString())) {
                                    return;
                                }
                                closePositionPrice.setText(lastestPriceValue);
                            }
                            break;
                    }
                    isgetPrice = false;
                }
            }
        });
        etAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    etAmount.setSelection(etAmount.getText().length());
                    currentQuantity = Integer.parseInt(s.toString());
                    minusQuantityLayout.setEnabled(true);
                    minusQuantityBtn.setImageResource(R.drawable.td_minus_icon);
                } else {
                    currentQuantity = 0;
                    minusQuantityLayout.setEnabled(false);
                    minusQuantityBtn.setImageResource(R.drawable.icon_gray_minus);
                }
            }
        });

        etAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    etAmount.setHint("");
                    etAmount.setCursorVisible(true);
                }
            }
        });
        etPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    etAmount.setHint("0");
                    etAmount.setCursorVisible(false);
                }
            }
        });
    }

    /*根据合约类型设置手数键盘header的解释文字*/
    private void setAmoutInputType(KeyboardUtil keyboardUtil) {
        if (TextUtils.equals(mTradeTypeCode, "Au(T+D)")
                || TextUtils.equals(mTradeTypeCode, "Ag(T+D)")) {
            etAmount.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM, KeyboardTouchListener.TYPE_ONE_THOUSAND));
        } else {
            etAmount.setOnTouchListener(new KeyboardTouchListener(keyboardUtil, KeyboardUtil.INPUTTYPE_NUM, KeyboardTouchListener.TYPE_ONE_HUNDRED));
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
      /*  if(isVisibleToUser) {
            sendRequestMsg(Market.InstType.AU_TD);
        }*/
    }

    @Override
    public void onResume() {
        super.onResume();
        new GetTradeTypeAsyncTask().execute(AsyncTask.TYPE_NET);
        new LoadMyAssetsAsyncTask().execute(AsyncTask.TYPE_NET);
        //new QueryPositionAmountAsyncTask().execute(AsyncTask.TYPE_NET);
        sendRequestMsg(instType);
    }

    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case HIDE_REMIND_HEAD:
                remindLayout.setVisibility(View.GONE);
                break;
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE:
                String message = (String) msg.obj;

                if (getActivity() != null && !getActivity().isFinishing()) {
                    ActivityUtils.forceQuit(getActivity(), message);
                }

                break;
        }
        return true;
    }

    //查询持仓类型
    public class GetTradeTypeAsyncTask extends AsyncTask<Void, Void, PositionType> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected PositionType doInBackground(Void... params) {
            try {
                PositionType positionType = TradeService.getInstance().getTradeType(mTradeTypeCode);
                if (positionType != null) {
                    return positionType;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(PositionType positionType) {
            super.onPostExecute(positionType);
            if (positionType == null) {
                return;
            }
            setButtonInfoBypositionType(positionType);
        }
    }

  /*  //查询持仓总量
    public class QueryPositionAmountAsyncTask extends AsyncTask<Void, Void, List<PositionAmount>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<PositionAmount> doInBackground(Void... params) {
            try {
                List<PositionAmount> positionAmounts = TradeService.getInstance().queryPositionAmount();
                Log.e("lf", "123");
                if (positionAmounts != null) {
                    return positionAmounts;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<PositionAmount> positionAmounts) {
            super.onPostExecute(positionAmounts);
            if (positionAmounts == null) {
                return;
            }
            getPositionAmounts(positionAmounts);
        }
    }

    *//*获取对应合约持仓总量*//*
    private void getPositionAmounts(List<PositionAmount> positionAmounts) {
        for (int i = 0; i < positionAmounts.size(); i++) {
            String prodCode = positionAmounts.get(i).getProdCode();
            int totalAmt = positionAmounts.get(i).getTotalAmt();
            if ("Au(T+D)".equals(prodCode)) {
                auTotalAmount = totalAmt;
            } else if ("mAu(T+D)".equals(prodCode)) {
                mAuTotalAmount = totalAmt;
            } else {
                agTotalAmount = totalAmt;
            }
        }
    }*/

    public class LoadMyAssetsAsyncTask extends AsyncTask<Void, Void, MyAssets> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected MyAssets doInBackground(Void... params) {

            try {
                MyAssets MyAssets = TradeService.getInstance().getMyAssets();
                return MyAssets;
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(MyAssets myAssets) {
            super.onPostExecute(myAssets);
            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            if (myAssets == null) {
                return;
            }
            dynamicEquity.setText(myAssets.getDynamicRights());
            availableAmount.setText(myAssets.getAvailableCash());
        }
    }


    private void setButtonInfoBypositionType(PositionType positionType) {
        currentPositionType = positionType.getType();
        switch (positionType.getType()) {
            case NO_POSITION:
                buyBtnTradetypeTxt.setText("买 多");
                soldBtnTradeTypeTxt.setText("卖 空");
                closePositionPrice.setText("无持仓");
                break;
            case SHORT_POSITIONS:
                buyBtnTradetypeTxt.setText("锁 仓");
                soldBtnTradeTypeTxt.setText("加 空");
                if (priceType == TYPE_QUEUING_PRICE) {
                    closePositionPrice.setText(soldOnePriceValue);
                } else if (priceType == TYPE_RIVAL_PRICE) {
                    closePositionPrice.setText(buyOnePriceValue);
                } else {
                    closePositionPrice.setText(lastestPriceValue);
                }
                break;
            case MULTIPLE_POSITIONS:
                buyBtnTradetypeTxt.setText("加 多");
                soldBtnTradeTypeTxt.setText("锁 仓");

                if (priceType == TYPE_QUEUING_PRICE) {
                    closePositionPrice.setText(soldOnePriceValue);
                } else if (priceType == TYPE_RIVAL_PRICE) {
                    closePositionPrice.setText(buyOnePriceValue);
                } else {
                    closePositionPrice.setText(lastestPriceValue);
                }
                break;
            case SHORT_AND_MULTIPLE_POSITIONS:
                buyBtnTradetypeTxt.setText("加 多");
                soldBtnTradeTypeTxt.setText("加 空");
                if (TextUtils.isEmpty(shortOrLongValue)) {
                    closePositionPrice.setText("锁 仓");
                }
                break;
        }

    }


    public class OrderTransactionAsyncTask extends AsyncTask<Void, Void, OrderResult> {
        public OrderTransactionAsyncTask() {
        }


        public OrderTransactionAsyncTask(String tradeTypeCode, String prodCode, String price, String volume) {
            mPositionTypeCode = tradeTypeCode;
            mTradeTypeCode = prodCode;
            mUnitPrice = price;
            totalVolume = StringConvertNumber.parseInt(volume);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected OrderResult doInBackground(Void... params) {
            try {
                OrderResult orderResult = TradeService.getInstance().orderTransaction(mPositionTypeCode, mTradeTypeCode, mUnitPrice, totalVolume + "");
                if (orderResult != null) {
                    return orderResult;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return null;
        }

        @Override
        protected void onPostExecute(OrderResult orderResult) {
            super.onPostExecute(orderResult);
            if (orderResult == null) {
                return;
            }
            if (orderResult.getStatus()) {
                showRemindLayout("下单成功", 1);
            } else {
                showRemindLayout(orderResult.getInfo(), 2);
            }
        }
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    /*重置当前价格类型下的数据*/
    private void setCurentSelectPriceTypeValue(String priceTypeTxt, int currentPriceType, String currentPrice) {
        etPrice.setText("");
        etPrice.setHint(priceTypeTxt);
        isgetPrice = false;
        priceType = currentPriceType;
        currentUnitPrice = MathUtils.stringToBigDecemal(currentPrice);
    }

    /*设置交易按钮的文字*/
    private void setTradeButtonText(String value1, String value2) {
        buyPrice.setText(value1);
        soldPrice.setText(value2);
    }

    private void initViewPager() {
        AdapterContent adapterContent = new AdapterContent(getChildFragmentManager(), getActivity());
        adapterContent.add(PositionsFragment.newInstance());
        adapterContent.add(EntrustFragment.newInstance());
        adapterContent.add(TransactionFragment.newInstance());
        mViewPager.setAdapter(adapterContent);
        mViewPager.setOffscreenPageLimit(2);
        idTabMenu.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.id_tab_home:
                        mPosition = 0;
                        idLineHome.setBackgroundColor(getResources().getColor(R.color.color_gold));
                        idLineMarket.setBackgroundColor(getResources().getColor(R.color.color_white));
                        idLineTrade.setBackgroundColor(getResources().getColor(R.color.color_white));
                        break;
                    case R.id.id_tab_market:
                        mPosition = 1;
                        idLineHome.setBackgroundColor(getResources().getColor(R.color.color_white));
                        idLineMarket.setBackgroundColor(getResources().getColor(R.color.color_gold));
                        idLineTrade.setBackgroundColor(getResources().getColor(R.color.color_white));
                        break;
                    case R.id.id_tab_trade:
                        idLineHome.setBackgroundColor(getResources().getColor(R.color.color_white));
                        idLineMarket.setBackgroundColor(getResources().getColor(R.color.color_white));
                        idLineTrade.setBackgroundColor(getResources().getColor(R.color.color_gold));
                        mPosition = 2;
                        break;
                }
                mViewPager.setCurrentItem(mPosition);
            }
        });

    }

    /*发送长连接合约请求*/
    private void sendRequestMsg(Market.InstType instType) {
        UserInfo userInfo = MyService.getInstance().getmUserInfo();
        String userName = "";
        if (userInfo != null) {
            userName = userInfo.getUserName();
        }

        Market.Identification.Builder builder = Market.Identification.newBuilder();
        builder.setCategory(Market.Category.ORDERPAGE);
        if (!TextUtils.isEmpty(userName)) {
            builder.setGoldExpertNo(userName);
        }
        builder.setInstType(instType);
        Market.Identification identification = builder.build();

        Market.Response response = Market.Response.newBuilder().setIdentification(identification).build();
        ChannelManager.sendMessage(0, response, 100175);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void oncontractTypeEventBus(ContractTypeEvent event) {
        refreshView();
        shortOrLongValue = event.getLongOrShort();
        if ("Au(T+D)".equals(event.getContractType())) {
            instType = Market.InstType.AU_TD;
            mTradeType = "黄金延期Au(T+D)";
        } else if ("mAu(T+D)".equals(event.getContractType())) {
            instType = Market.InstType.MAU_TD;
            mTradeType = "迷你黄金延期mAu(T+D)";
        } else {
            instType = Market.InstType.AG_TD;
            mTradeType = "白银延期Ag(T+D)";
        }
        sendRequestMsg(instType);
        switch (priceType) {
            case TYPE_RIVAL_PRICE:
                if ("多".equals(event.getLongOrShort())) {
                    closePositionPrice.setText(buyOnePriceValue);
                } else {
                    closePositionPrice.setText(soldOnePriceValue);
                }
                break;
            case TYPE_QUEUING_PRICE:
                if ("多".equals(event.getLongOrShort())) {
                    closePositionPrice.setText(soldOnePriceValue);
                } else {
                    closePositionPrice.setText(buyOnePriceValue);
                }
                break;
            case TYPE_NEWEST_PRICE:
                closePositionPrice.setText(lastestPriceValue);
                break;
        }
        mTradeTypeCode = event.getContractType();
        chooseType.setText(mTradeType);
        setAmoutInputType(keyboardUtil);
        new GetTradeTypeAsyncTask().execute(AsyncTask.TYPE_NET);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuoteDynaEventBus(DynaMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEDYNA) {
            fillMarketData(event.getQuoteDyna());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFiveRangeEventBus(FiveRangeMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEFIVERANGE) {
            fillFiveRangeData(event.getQuoteFiveRange());
        }
    }

    /*填充四档数据*/
    private void fillFiveRangeData(Market.QuoteFiveRange quoteFiveRange) {
        double lastSettle = StringConvertNumber.parseDouble(quoteFiveRange.getLastSettle());
        setItemValueAndColor(soldOnePrice, quoteFiveRange.getSellPrice1(), lastSettle);
        soldOnePriceValue = quoteFiveRange.getSellPrice1();
        soldOneQuantity.setText(String.valueOf(quoteFiveRange.getSellPolume1()));
        setItemValueAndColor(soldTwoPrice, quoteFiveRange.getSellPrice2(), lastSettle);
        soldTwoQuantity.setText(String.valueOf(quoteFiveRange.getSellPolume2()));
        setItemValueAndColor(buyOnePrice, quoteFiveRange.getBuyPrice1(), lastSettle);
        buyOnePriceValue = quoteFiveRange.getBuyPrice1();
        buyOneQuantity.setText(String.valueOf(quoteFiveRange.getBuyVolume1()));
        setItemValueAndColor(buyTwoPrice, quoteFiveRange.getBuyPrice2(), lastSettle);
        buyTwoQuantity.setText(String.valueOf(quoteFiveRange.getBuyVolume2()));
        if (!isgetPrice) {
            switch (priceType) {
                case TYPE_RIVAL_PRICE:
                    currentUnitPrice = MathUtils.stringToBigDecemal(quoteFiveRange.getSellPrice1());
                    setTradeButtonText(quoteFiveRange.getSellPrice1(), quoteFiveRange.getBuyPrice1());
                    if (!TextUtils.isEmpty(currentPositionType)) {
                        switch (currentPositionType) {
                            case SHORT_POSITIONS:
                                closePositionPrice.setText(soldOnePriceValue);
                                break;
                            case MULTIPLE_POSITIONS:
                                closePositionPrice.setText(buyOnePriceValue);
                                break;
                            case SHORT_AND_MULTIPLE_POSITIONS:
                                if (!TextUtils.isEmpty(shortOrLongValue)) {
                                    if ("多".equals(shortOrLongValue)) {
                                        closePositionPrice.setText(buyOnePriceValue);
                                    } else {
                                        closePositionPrice.setText(soldOnePriceValue);
                                    }
                                }
                        }

                    }

                    break;
                case TYPE_QUEUING_PRICE:
                    currentUnitPrice = MathUtils.stringToBigDecemal(quoteFiveRange.getBuyPrice1());
                    setTradeButtonText(quoteFiveRange.getBuyPrice1(), quoteFiveRange.getSellPrice1());
                    if (!TextUtils.isEmpty(currentPositionType)) {
                        switch (currentPositionType) {
                            case SHORT_POSITIONS:
                                closePositionPrice.setText(buyOnePriceValue);
                                break;
                            case MULTIPLE_POSITIONS:
                                closePositionPrice.setText(soldOnePriceValue);
                                break;
                            case SHORT_AND_MULTIPLE_POSITIONS:
                                if (!TextUtils.isEmpty(shortOrLongValue)) {
                                    if ("多".equals(shortOrLongValue)) {
                                        closePositionPrice.setText(soldOnePriceValue);
                                    } else {
                                        closePositionPrice.setText(buyOnePriceValue);
                                    }
                                }
                        }

                        break;
                    }
            }
        }

    }

    public void setItemValueAndColor(TextView item, String value, double lastSettle) {
        item.setText(value);
        double price = StringConvertNumber.parseDouble(value);
        if (lastSettle > price) {
            item.setTextColor(getResources().getColor(R.color.color_price_down));
        } else if (lastSettle == price) {
            item.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        } else {
            item.setTextColor(getResources().getColor(R.color.shallow_red));
        }

    }

    /*填充动态数据*/
    private void fillMarketData(Market.QuoteDyna quoteDyna) {
        if (!isgetPrice) {
            if (priceType == TYPE_NEWEST_PRICE) {
                currentUnitPrice = MathUtils.stringToBigDecemal(quoteDyna.getLastPrice());
                setTradeButtonText(quoteDyna.getLastPrice(), quoteDyna.getLastPrice());
                if (!TextUtils.isEmpty(closePositionPrice.getText().toString())) {
                    if ("锁 仓".equals(closePositionPrice.getText().toString()) || "无持仓".equals(closePositionPrice.getText().toString())) {
                        return;
                    }
                    closePositionPrice.setText(quoteDyna.getLastPrice());
                }
            }
        }

        String upDown = quoteDyna.getUpDownRate().substring(0, 1);
        if ("+".equals(upDown)) {
            newestGoldprice.setTextColor(getResources().getColor(R.color.shallow_red));
            goldRose.setTextColor(getResources().getColor(R.color.shallow_red));
        } else if ("-".equals(upDown)) {
            newestGoldprice.setTextColor(getResources().getColor(R.color.color_price_down));
            goldRose.setTextColor(getResources().getColor(R.color.color_price_down));
        } else {
            newestGoldprice.setTextColor(getResources().getColor(R.color.td_color_gray_two));
            goldRose.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        }
        newestGoldprice.setText(quoteDyna.getLastPrice());
        lastestPriceValue = quoteDyna.getLastPrice();
        goldRose.setText("(" + quoteDyna.getUpDownRate() + ")");
        hardenPrice.setText(quoteDyna.getHighestPrice());
        dropStopPrice.setText(quoteDyna.getLowestPrice());
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @OnClick({R.id.iv_close, R.id.sold_one_price_layout, R.id.sold_two_price_layout, R.id.buy_one_price_layout, R.id.buy_two_price_layout, R.id.lastest_price_layout, R.id.harden_price_layout, R.id.stop_price_layout, R.id.choose_type_layout, R.id.minus_price_layout, R.id.plus_price_layout, R.id.minus_quantity_layout, R.id.plus_quantity_layout, R.id.buy_layout, R.id.sell_layout, R.id.close_position_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                remindLayout.setVisibility(View.GONE);
                break;
            case R.id.sold_one_price_layout:
                movePrice(soldOnePrice);
                break;
            case R.id.sold_two_price_layout:
                movePrice(soldTwoPrice);
                break;
            case R.id.buy_one_price_layout:
                movePrice(buyOnePrice);
                break;
            case R.id.buy_two_price_layout:
                movePrice(buyTwoPrice);
                break;
            case R.id.lastest_price_layout:
                movePrice(newestGoldprice);
                break;
            case R.id.harden_price_layout:
                movePrice(hardenPrice);
                break;
            case R.id.stop_price_layout:
                movePrice(dropStopPrice);
                break;
            case R.id.choose_type_layout:
                Activity activity = getActivity();
                if (activity instanceof TDMainActivity) {
                    ((TDMainActivity) activity).getKeyBoardUtil().hideAllKeyBoard();
                }
                showContractTypePopupView();
                break;
            case R.id.minus_price_layout:
                isgetPrice = true;
                if (currentUnitPrice.toString().length() > 0) {
                    if (mTypeFlag == 0 || mTypeFlag == 1) {
                        currentUnitPrice = currentUnitPrice.subtract(BigDecimal.valueOf(0.01));
                    } else {
                        currentUnitPrice = currentUnitPrice.subtract(BigDecimal.valueOf(1));
                    }
                    etPrice.setText(currentUnitPrice.toString());
                }
                break;
            case R.id.plus_price_layout:
                isgetPrice = true;
                if (mTypeFlag == 0 || mTypeFlag == 1) {
                    currentUnitPrice = currentUnitPrice.add(BigDecimal.valueOf(0.01));
                } else {
                    currentUnitPrice = currentUnitPrice.add(BigDecimal.valueOf(1));
                }
                etPrice.setText(currentUnitPrice.toString());
                break;
            case R.id.minus_quantity_layout:
                if (currentQuantity >= 1) {
                    currentQuantity = currentQuantity - 1;
                    if (currentQuantity == 0) {
                        etAmount.setText("");
                    } else {
                        etAmount.setText(currentQuantity + "");
                    }
                }
                break;
            case R.id.plus_quantity_layout:
                if (currentQuantity < 99999) {
                    etAmount.setSelection(etAmount.getText().length());
                    currentQuantity = currentQuantity + 1;
                    etAmount.setText(currentQuantity + "");
                }
                break;
            case R.id.buy_layout:
                mPositionTypeCode = "4041";
                showOrderDialog(buyPrice.getText().toString(), "开多");
                break;
            case R.id.sell_layout:
                mPositionTypeCode = "4042";
                showOrderDialog(soldPrice.getText().toString(), "开空");
                break;
            case R.id.close_position_layout:
                if (!TextUtils.isEmpty(closePositionPrice.getText().toString())) {
                    if ("锁 仓".equals(closePositionPrice.getText().toString()) || "无持仓".equals(closePositionPrice.getText().toString())) {
                        return;
                    }
                    if (!TextUtils.isEmpty(shortOrLongValue) && "多".equals(shortOrLongValue)) {
                        mPositionTypeCode = "4043";
                        showOrderDialog(closePositionPrice.getText().toString(), "平多");
                    } else {
                        mPositionTypeCode = "4044";
                        showOrderDialog(closePositionPrice.getText().toString(), "平空");
                    }
                }
                break;
        }
    }

    private void showContractTypePopupView() {
        final List<TDTradeType> list = new ArrayList<>();
        TDTradeType tdTradeType1 = new TDTradeType();
        tdTradeType1.setTradeTypeName(getString(R.string.Au_delay));
        tdTradeType1.setTradeTypeCode("Au(T+D)");
        TDTradeType tdTradeType2 = new TDTradeType();
        tdTradeType2.setTradeTypeName(getString(R.string.mini_Au_delay));
        tdTradeType2.setTradeTypeCode("mAu(T+D)");
        TDTradeType tdTradeType3 = new TDTradeType();
        tdTradeType3.setTradeTypeName(getString(R.string.Ag_delay));
        tdTradeType3.setTradeTypeCode("Ag(T+D)");
        list.add(tdTradeType1);
        list.add(tdTradeType2);
        list.add(tdTradeType3);
        TDDropDownView typeDropView = new TDDropDownView(getActivity(),
                getActivity(), "选择种类", list);
        typeDropView.showAtLocation(activityTdmakeOrder, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        ActivityUtils.backgroundAlpha(getActivity(), 0.5f);
        typeDropView.setOnVauleClickListener(new Interface.OnTDTypeClickListener() {
            @Override
            public void onTypeSet(int value) {
                refreshView();
                chooseType.setText(list.get(value).getTradeTypeName());
                mTradeTypeCode = list.get(value).getTradeTypeCode();
                mTradeType = list.get(value).getTradeTypeName();
                mTypeFlag = value;
                if (value == 0) {
                    instType = Market.InstType.AU_TD;
                } else if (value == 1) {
                    instType = Market.InstType.MAU_TD;
                } else {
                    instType = Market.InstType.AG_TD;
                }
                sendRequestMsg(instType);
                setAmoutInputType(keyboardUtil);
                new GetTradeTypeAsyncTask().execute(AsyncTask.TYPE_NET);
            }
        });
        typeDropView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ActivityUtils.backgroundAlpha(getActivity(), 1f);
            }
        });
    }

    private void movePrice(TextView view) {
        isgetPrice = true;
        int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
        view.getLocationInWindow(start_location);// 这是获取当前点击的按钮在屏幕的X、Y坐标（这也是动画开始的坐标）
        TextView te = new TextView(getActivity());
        te.setText(view.getText());
        te.setGravity(Gravity.CENTER);
        move(te, start_location, view.getText().toString());
    }

    /*订单详情对话框*/
    public void showOrderDialog(String price, String tradeWay) {
        mUnitPrice = price;
        if (TextUtils.isEmpty(etAmount.getText().toString().trim())) {
            showRemindLayout("请输入手数", 2);
            return;
        }
        int volume = Integer.parseInt(etAmount.getText().toString().trim());
        totalVolume = volume;
        if (volume == 0) {
            showRemindLayout("手数不能为0", 2);
            return;
        }
        switch (mTradeTypeCode) {
            case "Au(T+D)":
                if (volume > 1000) {
                    showRemindLayout("已超过持仓限额，您当前可购的最大手数为" + 1000 + "手", 2);
                    return;
                }
                break;
            case "mAu(T+D)":
                if (volume > 10000) {
                    showRemindLayout("已超过持仓限额，您当前可购的最大手数为" + 10000 + "手", 2);
                    return;
                }
                break;
            case "Ag(T+D)":
                if (volume > 20000) {
                    showRemindLayout("已超过持仓限额，您当前可购的最大手数为" + 20000 + "手", 2);
                    return;
                }
                break;
        }
        if (StringConvertNumber.parseDouble(price) > StringConvertNumber.parseDouble(hardenPrice.getText().toString()) || StringConvertNumber.parseDouble(price) < StringConvertNumber.parseDouble(dropStopPrice.getText().toString())) {
            showRemindLayout("委托价格不应超出涨跌停板范围，请修改后下单", 2);
            return;
        } else {
            remindLayout.setVisibility(View.GONE);
        }
        TDSureOrderDialog orderDialog = new TDSureOrderDialog(getActivity(), mTradeType, tradeWay, price, volume + "", R.style.AlertDialogStyle);
        orderDialog.setOnSureListener(new TDSureOrderDialog.OnSureListener() {
            @Override
            public void sure() {
                new OrderTransactionAsyncTask().execute(AsyncTask.TYPE_NET);
            }

        });
        orderDialog.show();
    }


    public void showOrderDialog(final String tradeTypeCode, final String prodCode, final String price, String tradeWay, final String volume) {
        TDSureOrderDialog orderDialog = new TDSureOrderDialog(getActivity(), mTradeType, tradeWay, price, volume + "", R.style.AlertDialogStyle);
        orderDialog.setOnSureListener(new TDSureOrderDialog.OnSureListener() {
            @Override
            public void sure() {
                new OrderTransactionAsyncTask(tradeTypeCode, prodCode, price, volume).execute(AsyncTask.TYPE_NET);
            }

        });
        orderDialog.show();
    }

    private void showRemindLayout(String remindTxt, int type) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (type == 1) {
            ivComplete.setVisibility(View.VISIBLE);
            ivWarn.setVisibility(View.GONE);
        } else {
            ivComplete.setVisibility(View.GONE);
            ivWarn.setVisibility(View.VISIBLE);
        }
        remindLayout.setVisibility(View.VISIBLE);
        remindInfo.setText(remindTxt);
        int[] location = new int[2];
        int[] location1 = new int[2];
        remindLayout.getLocationOnScreen(location);
        remindLayout.getLocationInWindow(location1);
        TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, -location[1] - location1[1], location[1] - location[1]);
        translateAnimation.setDuration(800);
        remindLayout.startAnimation(translateAnimation);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = HIDE_REMIND_HEAD;
                handler.sendMessage(message);
            }
        }, 4000);
    }

    /*合约切换刷新布局*/
    private void refreshView() {
        isgetPrice = false;
        etAmount.setText("");
        etPrice.setText("");
        currentQuantity = 0;
        shortOrLongValue = "";
    }

    private void move(final View v, int[] start_location, final String text) {
        viewGroup = null;
        viewGroup = createAnimLayout();
        viewGroup.addView(v);// 把要移动的控件添加到动画层
        final View view = addViewToAnimLayout(viewGroup, v, start_location);
        int[] end_location = new int[2];// 这是用来存储动画结束位置的X、Y坐标
        etPrice.getLocationInWindow(end_location);
        int endX = 0 - start_location[0]
                + end_location[0];// 动画位移的X坐标
        int endY = end_location[1] - start_location[1];// 动画位移的y坐标
        TranslateAnimation translateAnimationX = new TranslateAnimation(0,
                endX, 0, 0);
        translateAnimationX.setInterpolator(new LinearInterpolator());
        translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true);

        TranslateAnimation translateAnimationY = new TranslateAnimation(0,
                0, 0, endY);
        translateAnimationY.setInterpolator(new AccelerateInterpolator());
        translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true);

        AnimationSet set = new AnimationSet(false);
        set.setFillAfter(false);
        set.addAnimation(translateAnimationY);
        set.addAnimation(translateAnimationX);
        set.setDuration(800);// 动画的执行时间
        view.startAnimation(set);
        // 动画监听事件
        set.setAnimationListener(new Animation.AnimationListener() {
            // 动画的开始
            @Override
            public void onAnimationStart(Animation animation) {
                v.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub
            }

            // 动画的结束
            @Override
            public void onAnimationEnd(Animation animation) {
                v.setVisibility(View.GONE);
                etPrice.setText(text);
            }
        });


    }

    /**
     * 创建动画层
     *
     * @return
     */
    private ViewGroup createAnimLayout() {
        ViewGroup rootView = (ViewGroup) getActivity().getWindow().getDecorView();
        LinearLayout animLayout = new LinearLayout(getActivity());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        animLayout.setLayoutParams(lp);
        animLayout.setBackgroundResource(android.R.color.transparent);
        rootView.addView(animLayout);
        return animLayout;
    }

    private View addViewToAnimLayout(final ViewGroup vg, final View view,
                                     int[] location) {
        int x = location[0];
        int y = location[1];
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = x;
        lp.topMargin = y;
        view.setLayoutParams(lp);
        return view;
    }


    @Override
    public void rivalPrice() {
        setCurentSelectPriceTypeValue("对手价", 0, soldOnePriceValue);
        setTradeButtonText(soldOnePriceValue, buyOnePriceValue);
        if (!TextUtils.isEmpty(shortOrLongValue)) {
            if ("多".equals(shortOrLongValue)) {
                closePositionPrice.setText(buyOnePriceValue);
            } else {
                closePositionPrice.setText(soldOnePriceValue);
            }
        }
    }

    @Override
    public void queuePrice() {
        setCurentSelectPriceTypeValue("排队价", 1, buyOnePriceValue);
        setTradeButtonText(buyOnePriceValue, soldOnePriceValue);
        if (!TextUtils.isEmpty(shortOrLongValue)) {
            if ("多".equals(shortOrLongValue)) {
                closePositionPrice.setText(soldOnePriceValue);
            } else {
                closePositionPrice.setText(buyOnePriceValue);
            }
        }
    }

    @Override
    public void lastedPrice() {
        setCurentSelectPriceTypeValue("最新价", 2, lastestPriceValue);
        setTradeButtonText(lastestPriceValue, lastestPriceValue);
        if (!TextUtils.isEmpty(closePositionPrice.getText().toString())) {
            if ("锁 仓".equals(closePositionPrice.getText().toString()) || "无持仓".equals(closePositionPrice.getText().toString())) {
                return;
            }
            closePositionPrice.setText(lastestPriceValue);
        }
    }

    public class LoadCancelOrderAsyncTask extends AsyncTask<Void, Void, EntrustStatus> {

        private String mOrderNo;

        public LoadCancelOrderAsyncTask(String orderNo) {
            this.mOrderNo = orderNo;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected EntrustStatus doInBackground(Void... params) {

            try {
                EntrustStatus entrustStatus = TradeService.getInstance().getEntrustStatus(mOrderNo);
                if (entrustStatus != null) {
                    return entrustStatus;
                }
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(EntrustStatus entrustStatus) {
            super.onPostExecute(entrustStatus);
            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            if (entrustStatus == null) {
                return;
            }
            if (!entrustStatus.getStatus()) {
                showRemindLayout("撤单失败", 2);
            }
        }
    }


}
